{% extends "admin/common_base.html" %}

{% block main %}

    <div class="main">
        <div class="body container">
            <div class="typecho-page-title">
                <h2>创建新页面</h2>
            </div>
            <div class="row typecho-page-main typecho-post-area" role="form">
                <form action="http://www.typecho.local/index.php/action/contents-page-edit?_=68260bde104205161f354c57ae946cbd" method="post"
                    name="write_page">
                    <div class="col-mb-12 col-tb-12" role="main">

                        <p class="title">
                            <label for="title" class="sr-only">标题</label>
                            <input type="text" id="title" name="title" autocomplete="off" value="" placeholder="标题" class="w-100 text title" />
                        </p>
                        <p class="mono url-slug">
                            <label for="slug" class="sr-only">网址缩略名</label>
                            www.typecho.local/index.php/
                            <input type="text" id="slug" name="slug" autocomplete="off" value=""
                                class="mono" />.html </p>
                        <p>
                            <label for="text" class="sr-only">页面内容</label>
                            <textarea style="height: 350px" autocomplete="off" id="text" name="text" class="w-100 mono"></textarea>
                        </p>

                        <p class="submit clearfix">
                            <span class="right">
                                <input type="hidden" name="cid" value="" />
                                <button type="submit" name="do" value="save" id="btn-save" class="btn">保存草稿</button>
                                <button type="submit" name="do" value="publish" class="btn primary" id="btn-submit">发布页面</button>
                                <input type="hidden" name="markdown" value="1" />
                            </span>
                        </p>

                    </div>
                </form>
            </div>
        </div>
    </div>

    {% endblock %}

    {% block footer %}
    <script>
        (function () {
            $(document).ready(function () {
                var error = $('.typecho-option .error:first');

                if (error.length > 0) {
                    $('html,body').scrollTop(error.parents('.typecho-option').offset().top);
                }

                $('form').submit(function () {
                    if (this.submitted) {
                        return false;
                    } else {
                        this.submitted = true;
                    }
                });

                $('label input[type=text]').click(function (e) {
                    var check = $('#' + $(this).parents('label').attr('for'));
                    check.prop('checked', true);
                    return false;
                });
            });
        })();
    </script>

    <script>
        $(document).ready(function () {
            // 聚焦
            $('#title').select();

            // text 自动拉伸
            Typecho.editorResize('text', 'http://www.typecho.local/index.php/action/ajax?do=editorResize&_=68260bde104205161f354c57ae946cbd');

            // 缩略名自适应宽度
            var slug = $('#slug');

            if (slug.length > 0) {
                var wrap = $('<div />').css({
                    'position': 'relative',
                    'display': 'inline-block'
                }),
                    justifySlug = $('<pre />').css({
                        'display': 'block',
                        'visibility': 'hidden',
                        'height': slug.height(),
                        'padding': '0 2px',
                        'margin': 0
                    }).insertAfter(slug.wrap(wrap).css({
                        'left': 0,
                        'top': 0,
                        'minWidth': '5px',
                        'position': 'absolute',
                        'width': '100%'
                    })), originalWidth = slug.width();

                function justifySlugWidth() {
                    var val = slug.val();
                    justifySlug.text(val.length > 0 ? val : '     ');
                }

                slug.bind('input propertychange', justifySlugWidth);
                justifySlugWidth();
            }

            // 原始的插入图片和文件
            Typecho.insertFileToEditor = function (file, url, isImage) {
                var textarea = $('#text'), sel = textarea.getSelection(),
                    html = isImage ? '<img src="' + url + '" alt="' + file + '" />'
                        : '<a href="' + url + '">' + file + '</a>',
                    offset = (sel ? sel.start : 0) + html.length;

                textarea.replaceSelection(html);
                textarea.setSelection(offset, offset);
            };

            var submitted = false, form = $('form[name=write_post],form[name=write_page]').submit(function () {
                submitted = true;
            }), formAction = form.attr('action'),
                idInput = $('input[name=cid]'),
                cid = idInput.val(),
                draft = $('input[name=draft]'),
                draftId = draft.length > 0 ? draft.val() : 0,
                btnSave = $('#btn-save').removeAttr('name').removeAttr('value'),
                btnSubmit = $('#btn-submit').removeAttr('name').removeAttr('value'),
                btnPreview = $('#btn-preview'),
                doAction = $('<input type="hidden" name="do" value="publish" />').appendTo(form),
                locked = false,
                changed = false,
                autoSave = $('<span id="auto-save-message" class="left"></span>').prependTo('.submit'),
                lastSaveTime = null;

            $(':input', form).bind('input change', function (e) {
                var tagName = $(this).prop('tagName');

                if (tagName.match(/(input|textarea)/i) && e.type == 'change') {
                    return;
                }

                changed = true;
            });

            form.bind('field', function () {
                changed = true;
            });

            // 发送保存请求
            function saveData(cb) {
                function callback(o) {
                    lastSaveTime = o.time;
                    cid = o.cid;
                    draftId = o.draftId;
                    idInput.val(cid);
                    autoSave.text('已保存' + ' (' + o.time + ')').effect('highlight', 1000);
                    locked = false;

                    btnSave.removeAttr('disabled');
                    btnPreview.removeAttr('disabled');

                    if (!!cb) {
                        cb(o)
                    }
                }

                changed = false;
                btnSave.attr('disabled', 'disabled');
                btnPreview.attr('disabled', 'disabled');
                autoSave.text('正在保存');

                if (typeof FormData !== 'undefined') {
                    var data = new FormData(form.get(0));
                    data.append('do', 'save');

                    $.ajax({
                        url: formAction,
                        processData: false,
                        contentType: false,
                        type: 'POST',
                        data: data,
                        success: callback
                    });
                } else {
                    var data = form.serialize() + '&do=save';
                    $.post(formAction, data, callback, 'json');
                }
            }

            // 计算夏令时偏移
            var dstOffset = (function () {
                var d = new Date(),
                    jan = new Date(d.getFullYear(), 0, 1),
                    jul = new Date(d.getFullYear(), 6, 1),
                    stdOffset = Math.max(jan.getTimezoneOffset(), jul.getTimezoneOffset());

                return stdOffset - d.getTimezoneOffset();
            })();

            if (dstOffset > 0) {
                $('<input name="dst" type="hidden" />').appendTo(form).val(dstOffset);
            }

            // 时区
            $('<input name="timezone" type="hidden" />').appendTo(form).val(- (new Date).getTimezoneOffset() * 60);

            // 自动保存

            // 自动检测离开页
            $(window).bind('beforeunload', function () {
                if (changed && !submitted) {
                    return '内容已经改变尚未保存, 您确认要离开此页面吗?';
                }
            });

            // 预览功能
            var isFullScreen = false;

            function previewData(cid) {
                isFullScreen = $(document.body).hasClass('fullscreen');
                $(document.body).addClass('fullscreen preview');

                var frame = $('<iframe frameborder="0" class="preview-frame preview-loading"></iframe>')
                    .attr('src', './preview.php?cid=' + cid)
                    .attr('sandbox', 'allow-scripts')
                    .appendTo(document.body);

                frame.load(function () {
                    frame.removeClass('preview-loading');
                });

                frame.height($(window).height() - 53);
            }

            function cancelPreview() {
                if (submitted) {
                    return;
                }

                if (!isFullScreen) {
                    $(document.body).removeClass('fullscreen');
                }

                $(document.body).removeClass('preview');
                $('.preview-frame').remove();
            };

            $('#btn-cancel-preview').click(cancelPreview);

            $(window).bind('message', function (e) {
                if (e.originalEvent.data == 'cancelPreview') {
                    cancelPreview();
                }
            });

            btnPreview.click(function () {
                if (changed) {
                    locked = true;

                    if (confirm('修改后的内容需要保存后才能预览, 是否保存?')) {
                        saveData(function (o) {
                            previewData(o.draftId);
                        });
                    } else {
                        locked = false;
                    }
                } else if (!!draftId) {
                    previewData(draftId);
                } else if (!!cid) {
                    previewData(cid);
                }
            });

            btnSave.click(function () {
                doAction.attr('value', 'save');
            });

            btnSubmit.click(function () {
                doAction.attr('value', 'publish');
            });

            // 控制选项和附件的切换
            var fileUploadInit = false;
            $('#edit-secondary .typecho-option-tabs li').click(function () {
                $('#edit-secondary .typecho-option-tabs li').removeClass('active');
                $(this).addClass('active');
                $(this).parents('#edit-secondary').find('.tab-content').addClass('hidden');

                var selected_tab = $(this).find('a').attr('href'),
                    selected_el = $(selected_tab).removeClass('hidden');

                if (!fileUploadInit) {
                    selected_el.trigger('init');
                    fileUploadInit = true;
                }

                return false;
            });

            // 高级选项控制
            $('#advance-panel-btn').click(function () {
                $('#advance-panel').toggle();
                return false;
            });

            // 自动隐藏密码框
            $('#visibility').change(function () {
                var val = $(this).val(), password = $('#post-password');

                if ('password' == val) {
                    password.removeClass('hidden');
                } else {
                    password.addClass('hidden');
                }
            });

            // 草稿删除确认
            $('.edit-draft-notice a').click(function () {
                if (confirm('您确认要删除这份草稿吗?')) {
                    window.location.href = $(this).attr('href');
                }

                return false;
            });
        });
    </script>

    <script src="http://www.typecho.local/admin/js/hyperdown.js?v=18.1.29"></script>
    <script src="http://www.typecho.local/admin/js/pagedown.js?v=18.1.29"></script>
    <script>
        $(document).ready(function () {
            var textarea = $('#text'),
                isFullScreen = false,
                toolbar = $('<div class="editor" id="wmd-button-bar" />').insertBefore(textarea.parent()),
                preview = $('<div id="wmd-preview" class="wmd-hidetab" />').insertAfter('.editor');

            var options = {}, isMarkdown = 1;

            options.strings = {
                bold: '加粗 <strong> Ctrl+B',
                boldexample: '加粗文字',

                italic: '斜体 <em> Ctrl+I',
                italicexample: '斜体文字',

                link: '链接 <a> Ctrl+L',
                linkdescription: '请输入链接描述',

                quote: '引用 <blockquote> Ctrl+Q',
                quoteexample: '引用文字',

                code: '代码 <pre><code> Ctrl+K',
                codeexample: '请输入代码',

                image: '图片 <img> Ctrl+G',
                imagedescription: '请输入图片描述',

                olist: '数字列表 <ol> Ctrl+O',
                ulist: '普通列表 <ul> Ctrl+U',
                litem: '列表项目',

                heading: '标题 <h1>/<h2> Ctrl+H',
                headingexample: '标题文字',

                hr: '分割线 <hr> Ctrl+R',
                more: '摘要分割线 <!--more--> Ctrl+M',

                undo: '撤销 - Ctrl+Z',
                redo: '重做 - Ctrl+Y',
                redomac: '重做 - Ctrl+Shift+Z',

                fullscreen: '全屏 - Ctrl+J',
                exitFullscreen: '退出全屏 - Ctrl+E',
                fullscreenUnsupport: '此浏览器不支持全屏操作',

                imagedialog: '<p><b>插入图片</b></p><p>请在下方的输入框内输入要插入的远程图片地址</p><p>您也可以使用附件功能插入上传的本地图片</p>',
                linkdialog: '<p><b>插入链接</b></p><p>请在下方的输入框内输入要插入的链接地址</p>',

                ok: '确定',
                cancel: '取消',

                help: 'Markdown语法帮助'
            };

            var converter = new HyperDown(),
                editor = new Markdown.Editor(converter, '', options);

            // 自动跟随
            converter.enableHtml(true);
            converter.enableLine(true);
            reloadScroll = scrollableEditor(textarea, preview);

            // 修正白名单
            converter.hook('makeHtml', function (html) {
                html = html.replace('<p><!--more--></p>', '<!--more-->');

                if (html.indexOf('<!--more-->') > 0) {
                    var parts = html.split(/\s*<\!\-\-more\-\->\s*/),
                        summary = parts.shift(),
                        details = parts.join('');

                    html = '<div class="summary">' + summary + '</div>'
                        + '<div class="details">' + details + '</div>';
                }

                // 替换block
                html = html.replace(/<(iframe|embed)\s+([^>]*)>/ig, function (all, tag, src) {
                    if (src[src.length - 1] == '/') {
                        src = src.substring(0, src.length - 1);
                    }

                    return '<div style="border: 1px solid #ccc; height: 40px; overflow: hidden; line-height: 40px; text-align: center; font-size: 12px; color: #777"><strong>'
                        + tag + '</strong> : ' + $.trim(src) + '</div>';
                });

                return html;
            });

            editor.hooks.chain('onPreviewRefresh', function () {
                var images = $('img', preview), count = images.length;

                if (count == 0) {
                    reloadScroll(true);
                } else {
                    images.load(function () {
                        count--;

                        if (count == 0) {
                            reloadScroll(true);
                        }
                    });
                }
            });


            var th = textarea.height(), ph = preview.height(),
                uploadBtn = $('<button type="button" id="btn-fullscreen-upload" class="btn btn-link">'
                    + '<i class="i-upload">附件</i></button>')
                    .prependTo('.submit .right')
                    .click(function () {
                        $('a', $('.typecho-option-tabs li').not('.active')).trigger('click');
                        return false;
                    });

            $('.typecho-option-tabs li').click(function () {
                uploadBtn.find('i').toggleClass('i-upload-active',
                    $('#tab-files-btn', this).length > 0);
            });

            editor.hooks.chain('enterFakeFullScreen', function () {
                th = textarea.height();
                ph = preview.height();
                $(document.body).addClass('fullscreen');
                var h = $(window).height() - toolbar.outerHeight();

                textarea.css('height', h);
                preview.css('height', h);
                isFullScreen = true;
            });

            editor.hooks.chain('enterFullScreen', function () {
                $(document.body).addClass('fullscreen');

                var h = window.screen.height - toolbar.outerHeight();
                textarea.css('height', h);
                preview.css('height', h);
                isFullScreen = true;
            });

            editor.hooks.chain('exitFullScreen', function () {
                $(document.body).removeClass('fullscreen');
                textarea.height(th);
                preview.height(ph);
                isFullScreen = false;
            });

            editor.hooks.chain('commandExecuted', function () {
                textarea.trigger('input');
            });

            function initMarkdown() {
                editor.run();

                var imageButton = $('#wmd-image-button'),
                    linkButton = $('#wmd-link-button');

                Typecho.insertFileToEditor = function (file, url, isImage) {
                    var button = isImage ? imageButton : linkButton;

                    options.strings[isImage ? 'imagename' : 'linkname'] = file;
                    button.trigger('click');

                    var checkDialog = setInterval(function () {
                        if ($('.wmd-prompt-dialog').length > 0) {
                            $('.wmd-prompt-dialog input').val(url).select();
                            clearInterval(checkDialog);
                            checkDialog = null;
                        }
                    }, 10);
                };

                Typecho.uploadComplete = function (file) {
                    Typecho.insertFileToEditor(file.title, file.url, file.isImage);
                };

                // 编辑预览切换
                var edittab = $('.editor').prepend('<div class="wmd-edittab"><a href="#wmd-editarea" class="active">撰写</a><a href="#wmd-preview">预览</a></div>'),
                    editarea = $(textarea.parent()).attr("id", "wmd-editarea");

                $(".wmd-edittab a").click(function () {
                    $(".wmd-edittab a").removeClass('active');
                    $(this).addClass("active");
                    $("#wmd-editarea, #wmd-preview").addClass("wmd-hidetab");

                    var selected_tab = $(this).attr("href"),
                        selected_el = $(selected_tab).removeClass("wmd-hidetab");

                    // 预览时隐藏编辑器按钮
                    if (selected_tab == "#wmd-preview") {
                        $("#wmd-button-row").addClass("wmd-visualhide");
                    } else {
                        $("#wmd-button-row").removeClass("wmd-visualhide");
                    }

                    // 预览和编辑窗口高度一致
                    $("#wmd-preview").outerHeight($("#wmd-editarea").innerHeight());

                    return false;
                });
            }

            if (isMarkdown) {
                initMarkdown();
            } else {
                var notice = $('<div class="message notice">这篇文章不是由Markdown语法创建的, 继续使用Markdown编辑它吗? '
                    + '<button class="btn btn-xs primary yes">是</button> '
                    + '<button class="btn btn-xs no">否</button></div>')
                    .hide().insertBefore(textarea).slideDown();

                $('.yes', notice).click(function () {
                    notice.remove();
                    $('<input type="hidden" name="markdown" value="1" />').appendTo('.submit');
                    initMarkdown();
                });

                $('.no', notice).click(function () {
                    notice.remove();
                });
            }
        });
    </script>


    <script src="http://www.typecho.local/admin/js/moxie.js?v=18.1.29"></script>
    <script src="http://www.typecho.local/admin/js/plupload.js?v=18.1.29"></script>
    <script>
        $(document).ready(function () {
            function updateAttacmentNumber() {
                var btn = $('#tab-files-btn'),
                    balloon = $('.balloon', btn),
                    count = $('#file-list li .insert').length;

                if (count > 0) {
                    if (!balloon.length) {
                        btn.html($.trim(btn.html()) + ' ');
                        balloon = $('<span class="balloon"></span>').appendTo(btn);
                    }

                    balloon.html(count);
                } else if (0 == count && balloon.length > 0) {
                    balloon.remove();
                }
            }

            $('.upload-area').bind({
                dragenter: function () {
                    $(this).parent().addClass('drag');
                },

                dragover: function (e) {
                    $(this).parent().addClass('drag');
                },

                drop: function () {
                    $(this).parent().removeClass('drag');
                },

                dragend: function () {
                    $(this).parent().removeClass('drag');
                },

                dragleave: function () {
                    $(this).parent().removeClass('drag');
                }
            });

            updateAttacmentNumber();

            function fileUploadStart(file) {
                $('<li id="' + file.id + '" class="loading">'
                    + file.name + '</li>').appendTo('#file-list');
            }

            function fileUploadError(error) {
                var file = error.file, code = error.code, word;

                switch (code) {
                    case plupload.FILE_SIZE_ERROR:
                        word = '文件大小超过限制';
                        break;
                    case plupload.FILE_EXTENSION_ERROR:
                        word = '文件扩展名不被支持';
                        break;
                    case plupload.FILE_DUPLICATE_ERROR:
                        word = '文件已经上传过';
                        break;
                    case plupload.HTTP_ERROR:
                    default:
                        word = '上传出现错误';
                        break;
                }

                var fileError = '%s 上传失败'.replace('%s', file.name),
                    li, exist = $('#' + file.id);

                if (exist.length > 0) {
                    li = exist.removeClass('loading').html(fileError);
                } else {
                    li = $('<li>' + fileError + '<br />' + word + '</li>').appendTo('#file-list');
                }

                li.effect('highlight', { color: '#FBC2C4' }, 2000, function () {
                    $(this).remove();
                });

                // fix issue #341
                this.removeFile(file);
            }

            var completeFile = null;
            function fileUploadComplete(id, url, data) {
                var li = $('#' + id).removeClass('loading').data('cid', data.cid)
                    .data('url', data.url)
                    .data('image', data.isImage)
                    .html('<input type="hidden" name="attachment[]" value="' + data.cid + '" />'
                    + '<a class="insert" target="_blank" href="###" title="点击插入文件">' + data.title + '</a><div class="info">' + data.bytes
                    + ' <a class="file" target="_blank" href="http://www.typecho.local/admin/media.php?cid='
                    + data.cid + '" title="编辑"><i class="i-edit"></i></a>'
                    + ' <a class="delete" href="###" title="删除"><i class="i-delete"></i></a></div>')
                    .effect('highlight', 1000);

                attachInsertEvent(li);
                attachDeleteEvent(li);
                updateAttacmentNumber();

                if (!completeFile) {
                    completeFile = data;
                }
            }

            $('#tab-files').bind('init', function () {
                var uploader = new plupload.Uploader({
                    browse_button: $('.upload-file').get(0),
                    url: 'http://www.typecho.local/index.php/action/upload?_=68260bde104205161f354c57ae946cbd',
                    runtimes: 'html5,flash,html4',
                    flash_swf_url: 'http://www.typecho.local/admin/js/Moxie.swf',
                    drop_element: $('.upload-area').get(0),
                    filters: {
                        max_file_size: '2mb',
                        mime_types: [{ 'title': '允许上传的文件', 'extensions': 'gif,jpg,jpeg,png,tiff,bmp' }],
                        prevent_duplicates: true
                    },

                    init: {
                        FilesAdded: function (up, files) {
                            for (var i = 0; i < files.length; i++) {
                                fileUploadStart(files[i]);
                            }

                            completeFile = null;
                            uploader.start();
                        },

                        UploadComplete: function () {
                            if (completeFile) {
                                Typecho.uploadComplete(completeFile);
                            }
                        },

                        FileUploaded: function (up, file, result) {
                            if (200 == result.status) {
                                var data = $.parseJSON(result.response);

                                if (data) {
                                    fileUploadComplete(file.id, data[0], data[1]);
                                    uploader.removeFile(file);
                                    return;
                                }
                            }

                            fileUploadError.call(uploader, {
                                code: plupload.HTTP_ERROR,
                                file: file
                            });
                        },

                        Error: function (up, error) {
                            fileUploadError.call(uploader, error);
                        }
                    }
                });

                uploader.init();
            });

            function attachInsertEvent(el) {
                $('.insert', el).click(function () {
                    var t = $(this), p = t.parents('li');
                    Typecho.insertFileToEditor(t.text(), p.data('url'), p.data('image'));
                    return false;
                });
            }

            function attachDeleteEvent(el) {
                var file = $('a.insert', el).text();
                $('.delete', el).click(function () {
                    if (confirm('确认要删除文件 %s 吗?'.replace('%s', file))) {
                        var cid = $(this).parents('li').data('cid');
                        $.post('http://www.typecho.local/index.php/action/contents-attachment-edit?_=68260bde104205161f354c57ae946cbd',
                            { 'do': 'delete', 'cid': cid },
                            function () {
                                $(el).fadeOut(function () {
                                    $(this).remove();
                                    updateAttacmentNumber();
                                });
                            });
                    }

                    return false;
                });
            }

            $('#file-list li').each(function () {
                attachInsertEvent(this);
                attachDeleteEvent(this);
            });
        });
    </script>
{% endblock %}